<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;

class PluginNavController extends Controller
{

    public function infos(Request $request)
    {
        Log::debug('PluginNavController->infos-----');
        $user = $request->user();
        $category = $request->input('category') ? : '';
        $navs = \App\PluginNav::setOptions(['with_children_hash'=>true])
            ->where('user_id', $user->id)
            ->where('pid',0)
            ->where('category',$category)
            ->orderBy('priority', 'desc')
            //->get()->keyBy('id');
            ->get();
//        $keyed = [];
//        foreach ($navs as $v) {
//            $keyed["{$v['id']}"] = $v;
//        }
        return response()->json($navs, 200);
    }

    public function save(Request $request)
    {
        $user = $request->user();
        $id = $request->input('id');
        $ntype = $request->input('ntype') ? : 'item';
        $pid = $request->input('pid') ? : 0;
        $address = ($ntype == 'item' ? ($request->input('address') ? : '') : '');

        $rules = [
            'display_name' => 'required|string|max:50',
        ];
        if($ntype == 'item') $rules['address'] = 'required|url';
        if($id == 0) $rules['category']   = ['required', Rule::in(['work','relax','explore'])];

        $this->validate($request, $rules);

        $nav = $id ? \App\PluginNav::where('user_id', $user->id)
            ->where('id', $id)->first() : (new \App\PluginNav);

        if($id == 0) {//create
            $nav->user_id = $user->id;
            $nav->ntype = $ntype;
            $nav->category = $request->input('category') ? : '';
            $nav->pid = $pid;
        }
        $nav->display_name = $request->input('display_name') ? : '';
        $nav->address = $address;
        $nav->save();
        return response()->json($nav, 200);
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $user = $request->user();
        \App\PluginNav::where('user_id', $user->id)
            ->where('id', $id)
            ->orWhere('pid', $id)->delete();
        return response()->make('', 204);
    }

    public function pin(Request $request)
    {
        $user = $request->user();

        $nav = \App\PluginNav::where('user_id', $user->id)
            ->where('id', $request->input('id'))->first();

        if (!$nav) {
            return response()->json(['message' => 'param error'], 422);
        }

        if($request->is_pin){
            $max = \App\PluginNav::where('user_id', $user->id)
                ->where('pid', $nav->category)
                ->where('pid', $nav->pid)->max('priority');

            $nav->priority = $max + 10;
        }else{
            $nav->priority = 0;
        }
        $nav->save();

        return response()->make('', 204);
    }
}
